package org.example.component;

import lombok.extern.slf4j.Slf4j;
import org.example.config.SmsConfig;
import org.example.util.CommonUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;

import javax.annotation.Resource;

/**
 * @description: 短信验证码组件
 * @author: 谢超
 * @date: 2023/7/17 13:42
 */
@Component
@Slf4j
public class SmsComponent {
    // 这是一个发送地址
    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码，基于阿里云购买的官方文档，启动类上面必须配置@EnableAsync才能使用@Async
     * @param to 发送对象，手机号码
     * @param templateId
     * @param value
     */
    @Async("threadPoolTaskExecutor")
    public void send (String to, String templateId, String value) {

        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = String.format(URL_TEMPLATE, to, templateId, value);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        httpHeaders.set("Authorization","APPCODE " + smsConfig.getAppCode());
        HttpEntity<Object> entity = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long endTime = CommonUtil.getCurrentTimestamp();

        log.info("耗时={}, url={}, body={}", endTime - beginTime, url, response.getBody());

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("发送短信验证码成功:{}", response.getBody());
        } else {
            log.info("发送短信验证码失败:{}", response.getBody());
        }

    }
}
